/*
libfmail: Socket abstraction

Copyright (C) 2007  Carlos Daniel Ruvalcaba Valenzuela <clsdaniel@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
    
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/ioctl.h>

#include <libfmail/socket.h>

Socket::Socket(){
    sock = socket(AF_INET, SOCK_STREAM, 0);
    self_addr = (struct sockaddr_in*)malloc(sizeof(struct sockaddr_in));
}

Socket::Socket(int s, struct sockaddr_in *addr){
    sock = s;
    self_addr = addr;
}

int Socket::Connect(char *remote_addr, int remote_port){
    int slen, r;
    struct in_addr p;
    
    if (!inet_aton(remote_addr, &p))
        return 0;
    
    self_addr->sin_family = AF_INET;
    self_addr->sin_port = htons(remote_port);
    self_addr->sin_addr.s_addr = p.s_addr;
    
    slen = sizeof(struct sockaddr_in);
    
    r = connect(sock, (struct sockaddr*)(self_addr), slen);
    return r;
}
    
int Socket::Bind(int port){
    int slen;
        
    self_addr->sin_family = AF_INET;
    self_addr->sin_port = htons(port);
    self_addr->sin_addr.s_addr = htonl(INADDR_ANY);
        
    slen = sizeof(struct sockaddr_in);
        
    return bind(sock, (struct sockaddr*)self_addr, slen);
}

int Socket::Listen(int queue){
    int r;
    r = listen(sock, queue);
    return r;
}

int Socket::Write(const char *buffer, int len){
    return write(sock, buffer, len);
}

int Socket::Read(char *buffer, int len){
    return read(sock, buffer, len);
}
    
Socket *Socket::Accept(){
    int client_socket;
    struct sockaddr_in *client;
    socklen_t clen;
    Socket *s;
    
    client = (struct sockaddr_in*)malloc(sizeof(struct sockaddr_in));
    clen = sizeof(struct sockaddr_in);
        
    client_socket = accept(sock, (struct sockaddr*)client, &clen);
    s = new Socket(client_socket, client);
        
    return s;
}

int Socket::Close(){
    return close(sock);
}

